﻿using System.Windows;
using System.Windows.Controls;
using System;

namespace Pfz.WpfControls
{
	/// <summary>
	/// This is a simple panel created to make the last control always show before the others,
	/// occupying all the content area. Is up to you to make the semi-transparent colors or
	/// to make them centered.
	/// </summary>
	public class SameAreaPanel:
		Panel
	{
		/// <summary>
		/// Sets the available size to all children.
		/// </summary>
		protected override Size MeasureOverride(Size availableSize)
		{
			double maxHeight = 0;
			double maxWidth = 0;
			
			var children = Children;
			if (children.Count == 0)
				return base.MeasureOverride(availableSize);

			foreach(UIElement child in children)
			{
				child.Measure(availableSize);
				var desiredSize = child.DesiredSize;

				maxWidth = Math.Max(desiredSize.Width, maxWidth);
				maxHeight = Math.Max(desiredSize.Height, maxHeight);
			}

			return new Size(maxWidth, maxHeight);
		}

		/// <summary>
		/// Arranges all childrenin the same finalSize.
		/// </summary>
		protected override Size ArrangeOverride(Size finalSize)
		{
			if (finalSize.Height == 0)
			{
				var parent = Parent as FrameworkElement;
				if (parent != null)
					finalSize = new Size(finalSize.Width, parent.ActualHeight);
			}

			var rectangle = new Rect(finalSize);
			foreach(UIElement child in Children)
				child.Arrange(rectangle);

			return finalSize;
		}
	}
}
